package com.mmall.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.mmall.common.Const;
import com.mmall.common.ResponseCode;
import com.mmall.common.ServerResponse;
import com.mmall.dao.CategoryMapper;
import com.mmall.dao.ProductMapper;
import com.mmall.pojo.Category;
import com.mmall.pojo.Product;
import com.mmall.service.ICategoryService;
import com.mmall.service.IProductService;
import com.mmall.utils.DateTimeUtil;
import com.mmall.utils.PropertiesUtil;
import com.mmall.vo.ProductDetailVo;
import com.mmall.vo.ProductListVo;
import net.sf.jsqlparser.schema.Server;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

@Service("iProductService")
public class ProductServiceImpl implements IProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private ICategoryService iCategoryService;

    public ServerResponse detail(Integer productId) {
        if (productId == null) {
            return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getMsg());
        }
        Product product = productMapper.selectByPrimaryKey(productId);
        if (product == null || product.getStatus() != Const.ProductStatus.ON_SALE) {
            return ServerResponse.createByErrorMessage("产品已下架或删除");
        }
        ProductDetailVo productDetailVo = assembleProductDetailVo(product);
        return ServerResponse.createBySuccess(productDetailVo);
    }

    private ProductDetailVo assembleProductDetailVo(Product product) {
        ProductDetailVo productDetailVo = new ProductDetailVo();
        productDetailVo.setId(product.getId());

        productDetailVo.setName(product.getName());
        productDetailVo.setTitle(product.getSubtitle());
        productDetailVo.setMainImage(PropertiesUtil.getProperty(Const.IMAGES_PREFIX,
                "http://happymall/") + product.getMainImage());
        productDetailVo.setSubImage(product.getSubImages());
        productDetailVo.setPrice(product.getPrice());
        productDetailVo.setStock(product.getStock());
        productDetailVo.setUpdateTime(DateTimeUtil.dateToStr(product.getUpdateTime()));
        productDetailVo.setCreateTime(DateTimeUtil.dateToStr(product.getCreateTime()));
        productDetailVo.setDetail(product.getDetail());

        //判断categoryId所对应的数据是否存在
        Category category = categoryMapper.selectByPrimaryKey(product.getCategoryId());
        if (category == null) {
            //不存在对应的种类信息
            productDetailVo.setCategoryId(0);
        } else {
            productDetailVo.setCategoryId(product.getCategoryId());
        }

        return productDetailVo;
    }


    public ServerResponse list(Integer categoryId, String keyword, int pageNum, int pageSize, String orderBy) {
        if (categoryId == null || StringUtils.isBlank(keyword)) {
            return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getMsg());
        }
        List<ProductListVo> productListVoList = Lists.newArrayList();
        Category category = categoryMapper.selectByPrimaryKey(categoryId);
        if (category == null && StringUtils.isBlank(keyword)) {
            //返回一个空的结果集，不报错
            PageHelper.startPage(pageNum, pageSize);
            PageInfo pageInfo = new PageInfo(productListVoList);
            return ServerResponse.createBySuccess(pageInfo);
        }

        List<Integer> categoryIdList = Lists.newArrayList();
        if (category != null) {
            Set<Category> categorySet = Sets.newHashSet();
            categoryIdList = iCategoryService.getSelfAndChildrenByCategoryId(category.getId()).getData();
        }

        if (StringUtils.isNotBlank(keyword)) {
            keyword = new StringBuilder().append("%").append(keyword).append("%").toString();
        }


        PageHelper.startPage(pageNum, pageSize);
        //设置排序方式
        if (StringUtils.isNotBlank(orderBy)) {
            String[] order = orderBy.split(Const.ProductOrder.SPLITE);
            PageHelper.orderBy(order[0] + " " + order[1]);
        }

        List<Product> products = productMapper.selectByCategoryIdAndKeywordSelective(categoryIdList, keyword);
        List<ProductListVo> productDetailVoList = Lists.newArrayList();
        for (Product product : products) {
            productDetailVoList.add(assembleProductListVo(product));
        }

        PageInfo pageInfo = new PageInfo(productListVoList);

        return ServerResponse.createBySuccess(pageInfo);

    }

    private ProductListVo assembleProductListVo(Product product) {
        ProductListVo productListVo = new ProductListVo();
        productListVo.setId(product.getId());
        productListVo.setCategoryId(product.getCategoryId());
        productListVo.setMainImage(product.getMainImage());
        productListVo.setName(product.getName());
        productListVo.setPrice(product.getPrice());
        productListVo.setStatus(product.getStatus());
        productListVo.setImageHost(PropertiesUtil.getProperty(Const.IMAGES_PREFIX, "http://happymall/"));

        return productListVo;
    }


    //Manager
    public ServerResponse listForManager(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Product> products = productMapper.selectAll();
        List<ProductListVo> productListVoList = Lists.newArrayList();
        if (products != null) {
            for (Product product : products) {
                productListVoList.add(assembleProductListVo(product));
            }
        }
        PageInfo pageInfo = new PageInfo(productListVoList);
        return ServerResponse.createBySuccess(pageInfo);

    }


    public ServerResponse searchProduct(String productName, int productId, int pageNum, int pageSize) {

        PageHelper.startPage(pageNum, pageSize);

        StringBuilder sb = new StringBuilder();

        if (StringUtils.isNotBlank(productName)) {
            productName = sb.append("%").append(productName).append("%").toString();
        }

        List<Product> products = productMapper.selectByProductIdOrName(productName, productId);
        List<ProductListVo> productListVoList = Lists.newArrayList();
        for (Product product : products) {
            productListVoList.add(assembleProductListVo(product));
        }

        //TODO
        PageInfo pageInfo = new PageInfo(productListVoList);
        return ServerResponse.createBySuccess(pageInfo);
    }


    public ServerResponse setSaleStatus(Integer productId, Integer status) {
        if (productId == null || status == null) {
            return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getMsg());
        }

        int count = productMapper.setSaleStatus(productId, status);
        if (count > 0) {
            return ServerResponse.createBySuccessMessage("更新产品状态成功");
        }
        return ServerResponse.createBySuccessMessage("更新产品状态失败");

    }

    public ServerResponse saveOrUpdateProduct(Product product) {
        if (product == null) {
            return ServerResponse.createByError(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getMsg());
        }
        //更新主图
        if (StringUtils.isNotBlank(product.getSubImages())) {
            String[] images = product.getSubImages().split(",");
            if (images.length > 0) {
                product.setMainImage(images[0]);
            }
        }
        if (product.getId() != null) {
            int count = productMapper.updateByPrimaryKeySelective(product);
            if (count > 0) {
                return ServerResponse.createBySuccessMessage("更新产品信息成功");
            }

        } else {
            int count = productMapper.insert(product);
            if (count > 0) {
                return ServerResponse.createBySuccessMessage("新增产品成功");
            }
        }
        return ServerResponse.createByErrorMessage("更新或新增产品失败");
    }


    public ServerResponse delete(Integer productId){
        if(productId!=null){
            int count = productMapper.deleteByPrimaryKey(productId);
            if(count>0){
                return ServerResponse.createBySuccessMessage("删除产品成功");
            }
        }
        return ServerResponse.createByErrorMessage("删除产品失败");
    }

}

